// RemotePlayerController.ts
import {  _decorator, Component, EventKeyboard, Input, input, KeyCode, SystemEvent, v2, Vec2 } from 'cc';
import { PlayerState } from './types';
import { GlobalEventMgr } from '../platform/event/GlobalEventMgr';
import { SyncDemoEvent } from './SyncDemoEvent';
const {ccclass, property} = _decorator;

@ccclass
export default class RemotePlayerController extends Component {
    @property
    public interpolationTime: number = 0.1; // 100ms插值
    
    // 状态管理
    private stateBuffer: PlayerState[] = [];
    private currentRenderState: PlayerState = new PlayerState();
    private targetState: PlayerState = new PlayerState();
    
    // 插值
    private interpolationTimer: number = 0;
    private isInterpolating: boolean = false;
    
    // 网络延迟补偿
    private networkLatency: number = 100;
    private maxBufferSize: number = 10;

    protected onLoad(): void {
        GlobalEventMgr.ins.addNotice(SyncDemoEvent.RemotePlayerStateUpdate, this,this.onServerStateUpdate);
    }
    
    update(dt: number) {
        this.updateInterpolation(dt);
    }
    
    // 接收服务器状态更新
    public onServerStateUpdate(serverState: PlayerState) {
        // 添加到状态缓冲区
        this.addStateToBuffer(serverState);
        
        // 应用航位推测
        this.applyDeadReckoning();
    }
    
    private addStateToBuffer(state: PlayerState) {
        this.stateBuffer.push(state.clone());
        
        // 保持缓冲区大小
        if (this.stateBuffer.length > this.maxBufferSize) {
            this.stateBuffer.shift();
        }
        
        // 排序缓冲区（按时间戳）
        this.stateBuffer.sort((a, b) => a.timestamp - b.timestamp);
    }
    
    // 航位推测法实现
    private applyDeadReckoning() {
        if (this.stateBuffer.length === 0) return;
        
        const currentTime = Date.now() - this.networkLatency;
        
        // 找到插值区间
        const interpolationStates = this.findInterpolationStates(currentTime);
        
        if (!interpolationStates) {
            // 使用最新状态进行推测
            this.predictFromLatestState(currentTime);
            return;
        }
        
        const {start, end, t} = interpolationStates;
        
        // 计算插值状态
        this.targetState.position = this.interpolatePosition(start, end, t);
        this.targetState.velocity = this.interpolateVelocity(start, end, t);
        // this.targetState.rotation = this.interpolateRotation(start, end, t);
        
        // 开始插值
        this.startInterpolation();
    }
    
    private findInterpolationStates(currentTime: number): {start: PlayerState, end: PlayerState, t: number} | null {
        if (this.stateBuffer.length < 2) return null;
        
        for (let i = this.stateBuffer.length - 1; i > 0; i--) {
            const start = this.stateBuffer[i - 1];
            const end = this.stateBuffer[i];
            
            if (currentTime >= start.timestamp && currentTime <= end.timestamp) {
                const totalTime = end.timestamp - start.timestamp;
                const elapsedTime = currentTime - start.timestamp;
                const t = Math.min(1, Math.max(0, elapsedTime / totalTime));
                
                return { start, end, t };
            }
        }
        
        return null;
    }
    
    private predictFromLatestState(currentTime: number) {
        const latestState = this.stateBuffer[this.stateBuffer.length - 1];
        const timeDiff = (currentTime - latestState.timestamp) / 1000;
        
        this.targetState.position = latestState.position.add(latestState.velocity.multiplyScalar(timeDiff));
        this.targetState.velocity = latestState.velocity.clone();
        // this.targetState.rotation = latestState.rotation;
        
        this.startInterpolation();
    }
    
    private startInterpolation() {
        this.isInterpolating = true;
        this.interpolationTimer = 0;
    }
    
    private updateInterpolation(dt: number) {
        if (!this.isInterpolating) return;
        
        this.interpolationTimer += dt;
        const t = Math.min(1, this.interpolationTimer / this.interpolationTime);
        
        // 平滑插值到目标位置
        const smoothedPosition = this.currentRenderState.position.lerp(
            this.targetState.position,
            t
        );
        
        this.node.setPosition(smoothedPosition.x, smoothedPosition.y);
        // this.node.rotation = misc.lerp(
        //     this.currentRenderState.rotation,
        //     this.targetState.rotation,
        //     t
        // );
        
        // 更新当前渲染状态
        this.currentRenderState.position = smoothedPosition;
        // this.currentRenderState.rotation = this.node.rotation;
        
        if (t >= 1) {
            this.isInterpolating = false;
        }
    }
    
    // 插值方法
    private interpolatePosition(start: PlayerState, end: PlayerState, t: number): Vec2 {
        return start.position.lerp(end.position, t);
    }
    
    private interpolateVelocity(start: PlayerState, end: PlayerState, t: number): Vec2 {
        return start.velocity.lerp(end.velocity, t);
    }
    
    // private interpolateRotation(start: PlayerState, end: PlayerState, t: number): number {
    //     return misc.lerp(start.rotation, end.rotation, t);
    // }
    
    // 动态调整网络延迟补偿
    public adjustNetworkLatency(newLatency: number) {
        this.networkLatency = newLatency;
    }
}